/*
Copyright (C) Alex S. (mailto: md5sum@alexsp.ru)

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details
http://www.gnu.org/licenses/gpl-2.0.html.

You should have received a copy of the GNU General Public License
along with this program in the file gpl-2.0.txt;
if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include <avr/io.h>
#include "stk500protocol.h"
#include "glcd_boot.h"

#define KEY_PIN	PINB
#define KEY_DDR DDRB
#define KEY_PORT PORTB
#define KEY_ENTER (1<<2)

void jmp_0(void) __attribute__ ((naked));
void jmp_0(void) {
	//	asm volatile ("jmp 0\n\t"::);
	(*(void(*)(void))(0))();
}

void usart_init(void) __attribute__ ((naked)) __attribute__ ((section (".init7")));
void usart_init() {
	UCSRA=(1<<U2X);
	UCSRB=(1<<RXEN)|(1<<TXEN);
	UCSRC=(1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0);
	UBRRL=F_CPU / (8L * USARTBAUD) -1;
}


void boot_condition_check(void) __attribute__ ((naked)) __attribute__ ((section (".init3")));
void boot_condition_check() {
	uint32_t cnt=0x8ffff;

	KEY_DDR&=~(KEY_ENTER);
	KEY_PORT|=(KEY_ENTER);
	__asm__ __volatile__("nop\r\n");
	if (pgm_read_byte(0)!=0xff) {
		while (cnt--) {if ((KEY_PIN&KEY_ENTER)) jmp_0();}
	}

	OCR2=20;
	TCCR2=(1<<WGM20)|(1<< WGM21)|(1<<COM21)|(0<<COM20)|(0<<CS22)|(1<<CS21)|(0<<CS20);
	DDRD|=(1<<PD7); /*Разрешим выход ШИМ*/

}
void next_baud();
uint16_t baud=USARTBAUD;
int main(){
#define KEYTMP 100
	uint8_t keytmp=0;

	GLCD_init();
	GLCD_xy(0,0);
	GLCD_print_logo(4,baud);
	for (;;) {
		if ((UCSRA&(1<<RXC))>0) {
			stk_buff_add(UDR);
		}
		if (stk_communicate==0) jmp_0();
		if (KEY_PIN&KEY_ENTER) {
			keytmp=KEY_ENTER;
		}else{
			if (keytmp) keytmp--;
			if (keytmp==1) next_baud();
		}
	}
	return 0;
}
void next_baud() {
	switch (baud) {
	case 38400:
		baud=9600;
		break;
	case 9600:
		baud=19200;
		break;
	case 19200:
		baud=38400;
		break;
	default:
		break;
	}
	GLCD_xy(0,0);
	GLCD_print_logo(4,baud);
	UBRRL=F_CPU / (8L * baud) -1;
}
